import React, { useEffect, useState } from 'react';
import { Modal, Table, Progress, Statistic, Row, Col, Card, Typography, Tag, Spin } from 'antd';
import { CheckCircleOutlined, ClockCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { getNotificationSendStatus } from '@/services/systemManagementApi';
import moment from 'moment';

const { Text, Title } = Typography;

interface SendStatusModalProps {
  visible: boolean;
  notification?: SYSTEM.NotificationModel;
  onCancel: () => void;
}

const SendStatusModal: React.FC<SendStatusModalProps> = ({ visible, notification, onCancel }) => {
  const [loading, setLoading] = useState(false);
  const [statusData, setStatusData] = useState<any>(null);

  useEffect(() => {
    if (visible && notification) {
      fetchSendStatus();
    }
  }, [visible, notification]);

  const fetchSendStatus = async () => {
    if (!notification) return;
    
    setLoading(true);
    try {
      const response = await getNotificationSendStatus(notification.id);
      setStatusData(response.data);
    } catch (error) {
      console.error('获取发送状态失败:', error);
    } finally {
      setLoading(false);
    }
  };

  if (!notification) return null;

  // 发送状态表格列
  const statusColumns = [
    {
      title: '用户ID',
      dataIndex: 'user_id',
      width: 80,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      width: 120,
      ellipsis: true,
    },
    {
      title: '发送状态',
      dataIndex: 'send_status',
      width: 100,
      render: (status: string) => {
        const statusMap = {
          success: { text: '发送成功', color: 'green', icon: <CheckCircleOutlined /> },
          pending: { text: '发送中', color: 'blue', icon: <ClockCircleOutlined /> },
          failed: { text: '发送失败', color: 'red', icon: <ExclamationCircleOutlined /> },
        };
        const config = statusMap[status] || statusMap.pending;
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        );
      },
    },
    {
      title: '阅读状态',
      dataIndex: 'read_status',
      width: 100,
      render: (status: string) => (
        <Tag color={status === 'read' ? 'green' : 'orange'}>
          {status === 'read' ? '已读' : '未读'}
        </Tag>
      ),
    },
    {
      title: '发送时间',
      dataIndex: 'sent_at',
      width: 140,
      render: (time: string) => time ? moment(time).format('MM-DD HH:mm:ss') : '-',
    },
    {
      title: '阅读时间',
      dataIndex: 'read_at',
      width: 140,
      render: (time: string) => time ? moment(time).format('MM-DD HH:mm:ss') : '-',
    },
    {
      title: '失败原因',
      dataIndex: 'error_message',
      ellipsis: true,
      render: (message: string) => message || '-',
    },
  ];

  const getProgressStatus = (percentage: number) => {
    if (percentage === 100) return 'success';
    if (percentage > 0) return 'active';
    return 'normal';
  };

  return (
    <Modal
      title={`发送状态 - ${notification.title}`}
      open={visible}
      onCancel={onCancel}
      footer={null}
      width={1000}
      destroyOnClose
    >
      <Spin spinning={loading}>
        {statusData && (
          <div>
            {/* 发送统计概览 */}
            <Row gutter={16} style={{ marginBottom: 24 }}>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="总发送数"
                    value={statusData.total_count || 0}
                    valueStyle={{ color: '#1890ff' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="发送成功"
                    value={statusData.success_count || 0}
                    valueStyle={{ color: '#52c41a' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="发送失败"
                    value={statusData.failed_count || 0}
                    valueStyle={{ color: '#ff4d4f' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="已读数量"
                    value={statusData.read_count || 0}
                    valueStyle={{ color: '#722ed1' }}
                  />
                </Card>
              </Col>
            </Row>

            {/* 发送进度 */}
            <Card title="发送进度" style={{ marginBottom: 16 }}>
              <div style={{ marginBottom: 16 }}>
                <Text strong>发送进度</Text>
                <Progress
                  percent={statusData.total_count > 0 
                    ? Math.round((statusData.success_count / statusData.total_count) * 100)
                    : 0
                  }
                  status={getProgressStatus(statusData.total_count > 0 
                    ? Math.round((statusData.success_count / statusData.total_count) * 100)
                    : 0
                  )}
                  style={{ marginTop: 8 }}
                />
              </div>
              <div>
                <Text strong>阅读进度</Text>
                <Progress
                  percent={statusData.success_count > 0 
                    ? Math.round((statusData.read_count / statusData.success_count) * 100)
                    : 0
                  }
                  status={getProgressStatus(statusData.success_count > 0 
                    ? Math.round((statusData.read_count / statusData.success_count) * 100)
                    : 0
                  )}
                  style={{ marginTop: 8 }}
                />
              </div>
            </Card>

            {/* 发送时间信息 */}
            <Card title="时间信息" style={{ marginBottom: 16 }}>
              <Row gutter={16}>
                <Col span={8}>
                  <Text type="secondary">开始发送时间：</Text>
                  <br />
                  <Text>{statusData.send_start_time 
                    ? moment(statusData.send_start_time).format('YYYY-MM-DD HH:mm:ss')
                    : '-'
                  }</Text>
                </Col>
                <Col span={8}>
                  <Text type="secondary">完成发送时间：</Text>
                  <br />
                  <Text>{statusData.send_end_time 
                    ? moment(statusData.send_end_time).format('YYYY-MM-DD HH:mm:ss')
                    : '-'
                  }</Text>
                </Col>
                <Col span={8}>
                  <Text type="secondary">发送耗时：</Text>
                  <br />
                  <Text>{statusData.send_duration || '-'}</Text>
                </Col>
              </Row>
            </Card>

            {/* 详细发送状态列表 */}
            <Card title="详细发送状态">
              <Table
                columns={statusColumns}
                dataSource={statusData.send_details || []}
                rowKey="user_id"
                size="small"
                pagination={{
                  pageSize: 10,
                  showSizeChanger: false,
                  showQuickJumper: true,
                }}
                scroll={{ y: 300 }}
              />
            </Card>

            {/* 错误统计 */}
            {statusData.error_summary && statusData.error_summary.length > 0 && (
              <Card title="错误统计" style={{ marginTop: 16 }}>
                <Table
                  columns={[
                    {
                      title: '错误类型',
                      dataIndex: 'error_type',
                      width: 150,
                    },
                    {
                      title: '错误信息',
                      dataIndex: 'error_message',
                      ellipsis: true,
                    },
                    {
                      title: '影响用户数',
                      dataIndex: 'affected_count',
                      width: 120,
                      render: (count: number) => (
                        <Tag color="red">{count}</Tag>
                      ),
                    },
                  ]}
                  dataSource={statusData.error_summary}
                  rowKey="error_type"
                  size="small"
                  pagination={false}
                />
              </Card>
            )}

            {/* 状态说明 */}
            <div style={{ 
              marginTop: 16, 
              padding: 12, 
              background: '#f6ffed', 
              border: '1px solid #b7eb8f',
              borderRadius: 6 
            }}>
              <h4 style={{ margin: '0 0 8px 0', color: '#52c41a' }}>状态说明</h4>
              <ul style={{ margin: 0, paddingLeft: 20, color: '#666' }}>
                <li><strong>发送成功：</strong>通知已成功推送到用户设备</li>
                <li><strong>发送中：</strong>通知正在发送队列中等待处理</li>
                <li><strong>发送失败：</strong>由于网络或其他原因发送失败</li>
                <li><strong>已读：</strong>用户已查看该通知</li>
                <li><strong>未读：</strong>用户尚未查看该通知</li>
              </ul>
            </div>
          </div>
        )}
      </Spin>
    </Modal>
  );
};

export default SendStatusModal;
